<script lang="ts" setup>
import { Toast } from "vant";
import Pubsub from "pubsub-js";
import { onMounted, onUnmounted, ref } from "vue";
import { PubSubEnum } from "@/types";
import ErrorMsgIcon from "@/img/error-message-icon.svg";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const showRef = ref<boolean>(false);
const textRef = ref<string>(t("tip.failed"));
const cbRef = ref<() => void>();

const showText = (
  _: string,
  params?: {
    text?: string;
    cb?: () => void;
  },
) => {
  textRef.value = params?.text || t("tip.failed");
  showRef.value = true;

  if (params?.cb) {
    cbRef.value = params.cb;
  }
};

onMounted(() => {
  Pubsub.subscribe(PubSubEnum.SHOW_ERROR_TIP, showText);
});

onUnmounted(() => {
  Pubsub.unsubscribe(PubSubEnum.SHOW_ERROR_TIP, showText);
});
const close = () => {
  if (cbRef.value) {
    cbRef.value();
    cbRef.value = undefined;
  }
};
</script>
<template>
  <Toast
    v-model:show="showRef"
    style="padding: 0; overflow: hidden; background-color: transparent"
    :duration="3000"
    @close="close"
  >
    <template #message>
      <div class="error-inner">
        <img :src="ErrorMsgIcon" :alt="ErrorMsgIcon" width="24" />
        <span>{{ textRef }}</span>
      </div>
    </template>
  </Toast>
</template>
<style lang="less" scoped>
@height: 73px;
.error-inner {
  width: 275px;
  background: linear-gradient(
    90deg,
    rgba(206, 112, 232, 1) 0%,
    rgba(223, 109, 180, 1) 51.39%,
    rgba(242, 106, 118, 1) 100%
  );
  height: 100%;
  border-radius: 10px;
  padding: 4px 16px 8px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 13px;
  color: rgba(255, 255, 255, 1);
  min-height: @height;

  span {
    line-height: 30px;
    text-align: center;
    word-break: break-word;
    margin-left: 10px;
  }
}
</style>
